<template>
  <div class="app-container">
    <!-- 左右分栏布局 -->
    <div class="main-layout">
      <!-- 左侧：用能结构树 -->
      <div class="left-panel">
        <EnergyUnitTree
          ref="energyUnitTreeRef"
          title="用能结构"
          :show-node-actions="true"
          :show-expand-toggle="false"
          :auto-select-first="true"
          @node-click="handleNodeClick"
          @node-add="handleAddWithPermission"
          @node-edit="handleUpdateWithPermission"
          @node-delete="handleDeleteWithPermission"
        />
      </div>

      <!-- 右侧：设备关联管理 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>关联设备管理</h3>
        </div>

        <!-- 设备筛选和操作 -->
        <div class="device-filter-container">
          <el-row :gutter="16" class="filter-row">
            <el-col :span="6">
              <el-select
                v-model="deviceFilter.energyType"
                placeholder="能源类型"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="item in ENERGY_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="deviceFilter.deviceTypeId"
                placeholder="设备类型"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="item in deviceTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-button
                type="primary"
                icon="Search"
                @click="searchAssociatedDevices"
                >搜索</el-button
              >
              <el-button
                type="primary"
                icon="Plus"
                @click="openDeviceSelector"
                :disabled="!selectedNode"
                style="margin-left: 8px"
                v-hasPermi="['device:energyUnit:associate']"
                >关联设备</el-button
              >
            </el-col>
          </el-row>
        </div>

        <!-- 设备列表 -->
        <div class="device-list-container">
          <div
            v-if="
              selectedNode &&
              filteredDeviceList &&
              filteredDeviceList.length > 0
            "
            class="table-wrapper"
          >
            <el-table
              :data="filteredDeviceList"
              v-loading="deviceLoading"
              height="100%"
            >
              <el-table-column prop="deviceCode" label="设备编号" width="150">
                <template #default="scope">
                  <span>{{
                    scope.row.deviceCode || scope.row.groupDeviceCode
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="deviceName"
                label="设备名称"
                width="120"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <span>{{
                    scope.row.deviceName || scope.row.groupDeviceName
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="deviceTypeName"
                label="设备类型"
                width="200"
              />
              <el-table-column label="能源类型" width="200">
                <template #default="scope">
                  <span
                    v-if="scope && scope.row"
                    class="custom-tag"
                    :class="getEnergyTypeClass(scope.row.energyType)"
                  >
                    {{ getEnergyTypeName(scope.row.energyType) }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                label="安装位置"
                show-overflow-tooltip
              />
              <!-- <el-table-column label="操作"  align="center">
                <template #default="scope">
                  <el-button v-if="scope && scope.$index !== undefined" type="text" size="small" icon="Delete" @click="removeDevice(scope.$index)">移除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <div v-else-if="selectedNode && !deviceLoading" class="empty-state">
            <el-empty description="该用能单元暂无关联设备" />
          </div>
          <div v-else-if="!selectedNode" class="empty-state">
            <el-empty description="请先选择用能单元，然后添加关联设备" />
          </div>
          <div v-else-if="deviceLoading" class="empty-state">
            <el-empty description="正在加载设备数据..." />
          </div>
        </div>

        <!-- 保存按钮 -->
        <div v-if="selectedNode" class="save-actions">
          <el-button
            type="primary"
            @click="saveDeviceAssociations"
            :loading="saving"
            v-hasPermi="['device:energyUnit:refresh']"
            >刷新设备列表</el-button
          >
        </div>
      </div>
    </div>

    <!-- 添加或修改用能单元对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="energyUnitRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上级用能单元" prop="parentGroupId">
              <el-tree-select
                v-model="form.parentGroupId"
                :data="energyUnitOptions"
                :props="{
                  children: 'children',
                  label: 'groupName',
                  value: 'groupId',
                }"
                placeholder="请选择上级用能单元"
                check-strictly
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用能单元名称" prop="groupName">
              <el-input
                v-model="form.groupName"
                placeholder="请输入用能单元名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用能单元类型" prop="groupType">
              <el-select
                v-model="form.groupType"
                placeholder="请选择用能单元类型"
              >
                <el-option
                  v-for="item in availableGroupTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="groupOrder">
              <el-input-number
                v-model="form.groupOrder"
                :min="0"
                :max="999"
                placeholder="请输入显示排序"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            v-hasPermi="['device:energyUnit:save']"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备关联弹窗 -->
    <el-dialog
      title="关联设备"
      v-model="showDeviceSelector"
      width="80%"
      top="2vh"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      class="device-association-dialog"
    >
      <div class="device-association-content">
        <!-- 主要内容区域 -->
        <div class="main-content">
          <el-row :gutter="20" class="content-row">
            <!-- 左侧：全量设备 -->
            <el-col :span="12">
              <div class="device-section available-section">
                <div class="section-header">
                  <h4>仪表待选区 ({{ availableDevices.length }}项)</h4>
                </div>

                <!-- 搜索条件 -->
                <div class="search-form">
                  <el-form :model="deviceQueryParams" inline>
                    <el-form-item label="名称">
                      <el-input
                        v-model="deviceQueryParams.name"
                        placeholder="请输入设备名称"
                        clearable
                        style="width: 150px"
                      />
                    </el-form-item>
                    <el-form-item label="">
                      <el-select
                        v-model="deviceQueryParams.deviceTypeId"
                        placeholder="设备类型"
                        clearable
                        style="width: 120px"
                      >
                        <el-option label="全部" value="" />
                        <el-option
                          v-for="item in deviceTypeList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="">
                      <el-select
                        v-model="deviceQueryParams.energyType"
                        placeholder="能源类型"
                        clearable
                        style="width: 120px"
                      >
                        <el-option label="全部" value="" />
                        <el-option
                          v-for="item in ENERGY_TYPE_OPTIONS"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        icon="Search"
                        @click="searchDevices"
                        :loading="deviceSearchLoading"
                        >搜索</el-button
                      >
                      <el-button @click="resetDeviceQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>

                <!-- 设备列表 -->
                <div class="table-container">
                  <el-table
                    :data="availableDevices"
                    v-loading="deviceSearchLoading"
                    height="250"
                    @selection-change="handleDeviceSelectionChange"
                    stripe
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column
                      prop="deviceCode"
                      label="设备编号"
                      width="150"
                    />
                    <el-table-column
                      prop="deviceName"
                      label="设备名称"
                      width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="deviceTypeName"
                      label="设备类型"
                      width="120"
                      show-overflow-tooltip
                    />

                    <el-table-column label="能源类型" width="120">
                      <template #default="scope">
                        <span
                          v-if="scope && scope.row"
                          class="custom-tag"
                          :class="getEnergyTypeClass(scope.row.energyType)"
                        >
                          {{ getEnergyTypeName(scope.row.energyType) }}
                        </span>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>

                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button
                          v-if="scope && scope.row"
                          type="text"
                          size="small"
                          @click="addSingleDevice(scope.row)"
                          >选中</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- 分页 -->
                  <el-pagination
                    :current-page="devicePagination.curPage"
                    :page-size="devicePagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="devicePagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handlePageSizeChange"
                    @current-change="handleCurrentPageChange"
                    class="pagination"
                  />
                </div>
              </div>
            </el-col>

            <!-- 右侧：已选设备 -->
            <el-col :span="12">
              <div class="device-section selected-section">
                <div class="section-header">
                  <h4>仪表已选区 ({{ deviceList.length }}项)</h4>
                  <el-input
                    v-model="selectedDeviceSearch"
                    placeholder="搜索器具名称"
                    clearable
                    style="width: 200px"
                    prefix-icon="Search"
                  />
                </div>

                <!-- 已选设备列表 -->
                <div class="table-container">
                  <el-table
                    :data="filteredSelectedDevices"
                    style="height: 300px"
                    stripe
                  >
                    <el-table-column
                      prop="deviceCode"
                      label="设备编号"
                      width="150"
                    >
                      <template #default="scope">
                        <span>{{
                          scope.row.deviceCode || scope.row.groupDeviceCode
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="deviceName"
                      label="设备名称"
                      width="120"
                      show-overflow-tooltip
                    >
                      <template #default="scope">
                        <span>{{
                          scope.row.deviceName || scope.row.groupDeviceName
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="deviceTypeName"
                      label="设备类型"
                      show-overflow-tooltip
                      width="120"
                    />

                    <el-table-column label="能源类型" width="120">
                      <template #default="scope">
                        <span
                          v-if="scope && scope.row"
                          class="custom-tag"
                          :class="getEnergyTypeClass(scope.row.energyType)"
                        >
                          {{ getEnergyTypeName(scope.row.energyType) }}
                        </span>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button
                          v-if="scope && scope.$index !== undefined"
                          type="text"
                          size="small"
                          @click="removeDevice(scope.$index)"
                          >撤销</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDeviceSelection">取消</el-button>
          <el-button
            type="primary"
            @click="confirmDeviceSelection"
            v-hasPermi="['device:energyUnit:saveAssociate']"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnergyUnit">
import {
  ref,
  reactive,
  toRefs,
  getCurrentInstance,
  nextTick,
  onMounted,
  computed,
  watch,
} from "vue";
import {
  listEnergyUnit,
  getEnergyUnit,
  delEnergyUnit,
  addEnergyUnit,
  updateEnergyUnit,
  getDeviceGroupList,
  delDevice,
  addDevice,
} from "@/api/deviceManage/energyUnit";
import { getDeviceList } from "@/api/deviceManage/device";
import { getDeviceTypeList } from "@/api/deviceManage/deviceType";
import EnergyUnitTree from "@/components/EnergyUnitTree/index.vue";
import {
  ENERGY_TYPE_OPTIONS,
  getEnergyTypeName,
  getEnergyTypeClass,
  ENERGY_UNIT_TYPE,
  ENERGY_UNIT_TYPE_OPTIONS,
  getEnergyUnitTypeName,
} from "@/utils/enums";

const { proxy } = getCurrentInstance() || {};
const { sys_normal_disable } = proxy?.useDict?.("sys_normal_disable") || {
  value: [],
};

// 基础数据
const open = ref(false);
const title = ref("");
const energyUnitOptions = ref([]);
const energyUnitTreeRef = ref(null);

// 设备相关
const deviceSearchLoading = ref(false);
const deviceOptions = ref([]);
const selectedNode = ref(null);
const deviceList = ref([]);
const originalDeviceList = ref([]); // 保存原始设备列表，用于对比
const deviceLoading = ref(false);
const saving = ref(false);
const showDeviceSelector = ref(false);
const availableDevices = ref([]);
const selectedDevices = ref([]);
const deviceTypeList = ref([]);

// 查询参数
const deviceQueryParams = reactive({
  name: "",
  deviceCode: "",
  deviceTypeId: null,
  energyType: null,
});

// 分页
const devicePagination = reactive({
  curPage: 1,
  pageSize: 20,
  total: 0,
});

// 设备筛选
const deviceFilter = reactive({
  energyType: "",
  deviceTypeId: "",
});

// 已选设备搜索
const selectedDeviceSearch = ref("");

// 用能单元类型选项（使用枚举）
const groupTypeOptions = ref(ENERGY_UNIT_TYPE_OPTIONS);

// 根据上级类型获取可选的子级类型
const getAvailableChildTypes = (parentType) => {
  const typeHierarchy = {
    [ENERGY_UNIT_TYPE.FACTORY]: [
      ENERGY_UNIT_TYPE.BUILDING,
      ENERGY_UNIT_TYPE.WORKSHOP,
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 工厂 -> 楼栋、车间、工序、设备
    [ENERGY_UNIT_TYPE.BUILDING]: [
      ENERGY_UNIT_TYPE.WORKSHOP,
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 楼栋 -> 车间、工序、设备
    [ENERGY_UNIT_TYPE.WORKSHOP]: [
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 车间 -> 工序、设备
    [ENERGY_UNIT_TYPE.PROCESS]: [ENERGY_UNIT_TYPE.EQUIPMENT], // 工序 -> 设备
    [ENERGY_UNIT_TYPE.EQUIPMENT]: [], // 设备 -> 无子级
  };

  return typeHierarchy[parentType] || [];
};

// 根据上级类型获取可选的类型（包括等于和小于）
const getAvailableTypes = (parentType) => {
  const typeHierarchy = {
    [ENERGY_UNIT_TYPE.FACTORY]: [
      ENERGY_UNIT_TYPE.FACTORY,
      ENERGY_UNIT_TYPE.BUILDING,
      ENERGY_UNIT_TYPE.WORKSHOP,
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 工厂 -> 工厂、楼栋、车间、工序、设备
    [ENERGY_UNIT_TYPE.BUILDING]: [
      ENERGY_UNIT_TYPE.BUILDING,
      ENERGY_UNIT_TYPE.WORKSHOP,
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 楼栋 -> 楼栋、车间、工序、设备
    [ENERGY_UNIT_TYPE.WORKSHOP]: [
      ENERGY_UNIT_TYPE.WORKSHOP,
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 车间 -> 车间、工序、设备
    [ENERGY_UNIT_TYPE.PROCESS]: [
      ENERGY_UNIT_TYPE.PROCESS,
      ENERGY_UNIT_TYPE.EQUIPMENT,
    ], // 工序 -> 工序、设备
    [ENERGY_UNIT_TYPE.EQUIPMENT]: [ENERGY_UNIT_TYPE.EQUIPMENT], // 设备 -> 设备
  };

  return typeHierarchy[parentType] || [];
};

// 表单数据
const data = reactive({
  form: {
    groupId: undefined,
    parentGroupId: undefined,
    parentGroupName: undefined,
    groupName: undefined,
    groupType: undefined,
    groupOrder: 0,
    status: "0",
    deviceId: undefined,
  },
  queryParams: {
    groupName: undefined,
    groupType: undefined,
    status: undefined,
  },
  rules: {
    parentGroupId: [
      {
        required: true,
        message: "上级用能单元不能为空",
        trigger: "blur",
        validator: (rule, value, callback) => {
          if (
            form.value.parentGroupId !== 0 &&
            form.value.parentGroupId !== undefined
          ) {
            if (!value) {
              callback(new Error("上级用能单元不能为空"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
      },
    ],
    groupName: [
      { required: true, message: "用能单元名称不能为空", trigger: "blur" },
    ],
    groupType: [
      { required: true, message: "用能单元类型不能为空", trigger: "change" },
    ],
    groupOrder: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 计算可选的用能单元类型
const availableGroupTypes = computed(() => {
  if (!form.value.parentGroupId) {
    // 如果没有上级，可以选择所有类型
    return groupTypeOptions.value;
  }

  // 根据上级类型获取可选的类型
  const parentType = getParentTypeById(form.value.parentGroupId);
  let availableTypes;

  if (form.value.groupId) {
    // 修改模式：可以选择小于等于上级类型的类型
    availableTypes = getAvailableTypes(parentType);
  } else {
    // 新增模式：只能选择小于上级类型的类型
    availableTypes = getAvailableChildTypes(parentType);
  }

  return groupTypeOptions.value.filter((option) =>
    availableTypes.includes(option.value)
  );
});

// 根据ID获取上级类型
const getParentTypeById = (parentId) => {
  if (!parentId) return null;

  const findTypeById = (items) => {
    for (const item of items) {
      if (item.groupId === parentId) {
        return item.groupType;
      }
      if (item.children && item.children.length > 0) {
        const found = findTypeById(item.children);
        if (found !== null) return found;
      }
    }
    return null;
  };

  return findTypeById(energyUnitOptions.value);
};

// 监听上级用能单元变化，重置用能单元类型
watch(
  () => form.value.parentGroupId,
  (newParentId) => {
    if (newParentId) {
      // 清空当前选择的类型
      form.value.groupType = undefined;
    }
  }
);

// 计算过滤后的设备列表
const filteredDeviceList = computed(() => {
  if (!deviceList.value || !Array.isArray(deviceList.value)) return [];

  return deviceList.value.filter((device) => {
    const energyTypeMatch =
      !deviceFilter.energyType || device.energyType == deviceFilter.energyType;
    const deviceTypeMatch =
      !deviceFilter.deviceTypeId ||
      device.deviceTypeId == deviceFilter.deviceTypeId;
    return energyTypeMatch && deviceTypeMatch;
  });
});

// 计算过滤后的已选设备列表
const filteredSelectedDevices = computed(() => {
  if (!deviceList.value || !Array.isArray(deviceList.value)) return [];

  if (!selectedDeviceSearch.value) return deviceList.value;

  return deviceList.value.filter((device) =>
    device.deviceName
      ?.toLowerCase()
      .includes(selectedDeviceSearch.value.toLowerCase())
  );
});

// 工具函数

// 设备相关函数
function initDeviceOptions() {
  getDeviceList({ curPage: 1, pageSize: 20 })
    .then((response) => {
      deviceOptions.value = response.data.list || [];
    })
    .catch(() => {
      deviceOptions.value = [];
    });
}

function searchDevices() {
  deviceSearchLoading.value = true;
  const params = {
    ...deviceQueryParams,
    curPage: devicePagination.curPage,
    pageSize: devicePagination.pageSize,
  };

  getDeviceList(params)
    .then((response) => {
      availableDevices.value = response.data.list || [];
      devicePagination.total = response.data.totalCount || 0;
      deviceSearchLoading.value = false;
    })
    .catch(() => {
      availableDevices.value = [];
      deviceSearchLoading.value = false;
    });
}

function resetDeviceQuery() {
  deviceQueryParams.name = "";
  deviceQueryParams.deviceCode = "";
  deviceQueryParams.deviceTypeId = null;
  deviceQueryParams.energyType = null;
  devicePagination.curPage = 1;
  searchDevices();
}

// 搜索关联设备
function searchAssociatedDevices() {
  // 这里可以根据筛选条件重新加载设备数据
  // 目前使用计算属性进行前端筛选
}

// 添加单个设备（弹窗内本地操作）
function addSingleDevice(device) {
  if (deviceList.value.some((existing) => existing.id === device.id)) {
    proxy?.$modal?.msgWarning?.("设备已存在");
    return;
  }

  deviceList.value.push(device);
  proxy?.$modal?.msgSuccess?.("设备已添加到待选区");
}

// 确认设备选择
function confirmDeviceSelection() {
  if (!selectedNode.value) {
    proxy?.$modal?.msgWarning?.("请先选择用能单元");
    return;
  }

  // 对比原始列表和当前列表，找出新增和删除的设备
  const originalIds = originalDeviceList.value.map((device) => device.id);
  const currentIds = deviceList.value.map((device) => device.id);

  // 找出新增的设备
  const addedDevices = deviceList.value.filter(
    (device) => !originalIds.includes(device.id)
  );

  // 找出删除的设备
  const removedDevices = originalDeviceList.value.filter(
    (device) => !currentIds.includes(device.id)
  );

  // 如果没有变化，直接关闭弹窗
  if (addedDevices.length === 0 && removedDevices.length === 0) {
    showDeviceSelector.value = false;
    proxy?.$modal?.msgInfo?.("没有设备变更");
    return;
  }

  // 执行批量操作
  const promises = [];

  // 批量添加设备
  if (addedDevices.length > 0) {
    const deviceGroupList = addedDevices.map((device) => ({
      deviceId: device.id,
      groupId: selectedNode.value.groupId,
      groupDeviceId: device.id,
    }));
    promises.push(addDevice(deviceGroupList));
  }

  // 批量删除设备
  if (removedDevices.length > 0) {
    const deviceIds = removedDevices.map((device) => device.id);
    promises.push(delDevice(deviceIds));
  }

  // 等待所有操作完成
  Promise.all(promises)
    .then(() => {
      // 更新原始设备列表
      originalDeviceList.value = [...deviceList.value];

      showDeviceSelector.value = false;
      selectedDevices.value = [];

      let message = "设备关联更新成功";
      if (addedDevices.length > 0 && removedDevices.length > 0) {
        message = `成功添加 ${addedDevices.length} 个设备，移除 ${removedDevices.length} 个设备`;
      } else if (addedDevices.length > 0) {
        message = `成功添加 ${addedDevices.length} 个设备`;
      } else if (removedDevices.length > 0) {
        message = `成功移除 ${removedDevices.length} 个设备`;
      }

      proxy?.$modal?.msgSuccess?.(message);
    })
    .catch((error) => {
      console.error("批量更新设备失败:", error);
      proxy?.$modal?.msgError?.("批量更新设备失败");
      // 恢复原始列表
      deviceList.value = [...originalDeviceList.value];
    });
}

// 取消设备选择
function cancelDeviceSelection() {
  // 恢复原始设备列表
  deviceList.value = [...originalDeviceList.value];
  showDeviceSelector.value = false;
  selectedDevices.value = [];
}

// 打开设备选择器
function openDeviceSelector() {
  if (!selectedNode.value) {
    proxy?.$modal?.msgWarning?.("请先选择用能单元");
    return;
  }

  // 保存原始设备列表
  originalDeviceList.value = [...deviceList.value];

  showDeviceSelector.value = true;
  // 重置查询参数
  resetDeviceQuery();
  // 加载全量设备数据
  searchDevices();
}

function handlePageSizeChange(size) {
  devicePagination.pageSize = size;
  devicePagination.curPage = 1;
  searchDevices();
}

function handleCurrentPageChange(page) {
  devicePagination.curPage = page;
  searchDevices();
}

function handleDeviceSelectionChange(selection) {
  selectedDevices.value = selection || [];
}

function removeDevice(index) {
  if (index === undefined || index < 0 || index >= deviceList.value.length) {
    proxy?.$modal?.msgWarning?.("请选择要移除的设备");
    return;
  }

  const device = deviceList.value[index];
  if (!device || !device.id) {
    proxy?.$modal?.msgWarning?.("设备信息不完整");
    return;
  }

  // 直接移除，不调用接口
  deviceList.value.splice(index, 1);
  proxy?.$modal?.msgSuccess?.("设备已从待选区移除");
}

function saveDeviceAssociations() {
  if (!selectedNode.value) {
    proxy?.$modal?.msgWarning?.("请先选择用能单元");
    return;
  }

  // 刷新设备列表
  loadUnitDevices(selectedNode.value.groupId);
  proxy?.$modal?.msgSuccess?.("设备列表已刷新");
}

// 树相关函数
function handleNodeClick(data) {
  if (!data || !data.groupName) return;
  try {
    selectedNode.value = data;
    loadUnitDevices(data.groupId);
  } catch (error) {
    console.error("节点点击处理失败:", error);
  }
}

function loadUnitDevices(groupId) {
  if (!groupId) {
    deviceList.value = [];
    originalDeviceList.value = [];
    return;
  }

  deviceLoading.value = true;
  getDeviceGroupList(groupId)
    .then((response) => {
      deviceList.value = response.data || [];
      originalDeviceList.value = [...deviceList.value]; // 保存原始列表
      deviceLoading.value = false;
    })
    .catch((error) => {
      console.error("获取分组设备失败:", error);
      deviceList.value = [];
      originalDeviceList.value = [];
      deviceLoading.value = false;
      proxy?.$modal?.msgError?.("获取设备列表失败");
    });
}

// 权限检查函数
function handleAddWithPermission(row) {
  // 检查新增权限
  if (!proxy?.$auth?.hasPermi?.("device:energyUnit:add")) {
    proxy?.$modal?.msgWarning?.("您没有新增用能单元的权限");
    return;
  }
  handleAdd(row);
}

function handleUpdateWithPermission(row) {
  // 检查编辑权限
  if (!proxy?.$auth?.hasPermi?.("device:energyUnit:edit")) {
    proxy?.$modal?.msgWarning?.("您没有编辑用能单元的权限");
    return;
  }
  handleUpdate(row);
}

function handleDeleteWithPermission(row) {
  // 检查删除权限
  if (!proxy?.$auth?.hasPermi?.("device:energyUnit:remove")) {
    proxy?.$modal?.msgWarning?.("您没有删除用能单元的权限");
    return;
  }
  handleDelete(row);
}

// 主要功能函数

function reset() {
  form.value = {
    groupId: undefined,
    parentGroupId: undefined,
    parentGroupName: undefined,
    groupName: undefined,
    groupType: undefined,
    groupOrder: 0,
    status: "0",
    deviceId: undefined,
  };
  proxy?.resetForm?.("energyUnitRef");
}

function handleAdd(row) {
  reset();

  // 从树组件获取数据
  if (energyUnitTreeRef.value) {
    energyUnitOptions.value = energyUnitTreeRef.value.getTreeData();
  }

  if (row && row.groupId) {
    form.value.parentGroupId = row.groupId;
  }

  open.value = true;
  title.value = "添加用能单元";
}

function handleUpdate(row) {
  // 从树组件获取数据
  if (energyUnitTreeRef.value) {
    energyUnitOptions.value = energyUnitTreeRef.value.getTreeData();
  }

  if (row && row.groupId) {
    getEnergyUnit(row.groupId).then((detailResponse) => {
      // 先重置表单，再设置数据
      reset();
      form.value = detailResponse.data || {};
      form.value.status = String(form.value.status);
      // 确保 groupType 是数字类型
      form.value.groupType = Number(form.value.groupType);
      open.value = true;
      title.value = "修改用能单元";
    });
  }
}

function submitForm() {
  proxy?.$refs?.["energyUnitRef"]?.validate?.((valid) => {
    if (valid) {
      const submitData = {
        ...form.value,
        status: parseInt(form.value.status),
      };

      if (form.value.groupId != undefined) {
        updateEnergyUnit(submitData)
          .then(() => {
            proxy?.$modal?.msgSuccess?.("修改成功");
            open.value = false;
            // 刷新树组件
            if (energyUnitTreeRef.value) {
              energyUnitTreeRef.value.refresh();
            }
          })
          .catch((error) => {
            console.error("修改失败:", error);
            proxy?.$modal?.msgError?.("修改失败");
          });
      } else {
        addEnergyUnit(submitData)
          .then(() => {
            proxy?.$modal?.msgSuccess?.("新增成功");
            open.value = false;
            // 刷新树组件
            if (energyUnitTreeRef.value) {
              energyUnitTreeRef.value.refresh();
            }
          })
          .catch((error) => {
            console.error("新增失败:", error);
            proxy?.$modal?.msgError?.("新增失败");
          });
      }
    }
  });
}

function handleDelete(row) {
  if (!row || !row.groupId) return;

  const isRoot = row.parentGroupId == 0;
  const message = isRoot
    ? `是否确认删除根节点用能单元"${row.groupName}"？删除后其所有子节点也将被删除！`
    : `是否确认删除用能单元"${row.groupName}"？`;

  proxy?.$modal
    ?.confirm?.(message, "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      return delEnergyUnit([row.groupId]);
    })
    .then(() => {
      // 刷新树组件
      if (energyUnitTreeRef.value) {
        energyUnitTreeRef.value.refresh();
      }
      proxy?.$modal?.msgSuccess?.("删除成功");
    })
    .catch((error) => {
      console.error("删除失败:", error);
      proxy?.$modal?.msgInfo?.("已取消删除");
    });
}

function cancel() {
  open.value = false;
  reset();
}

// 页面初始化
onMounted(() => {
  try {
    // 确保 deviceList 始终是有效数组
    if (!Array.isArray(deviceList.value)) {
      deviceList.value = [];
    }

    initDeviceOptions();
    getDeviceTypeList()
      .then((res) => {
        deviceTypeList.value = res.data.list || [];
      })
      .catch((error) => {
        console.error("获取设备类型列表失败:", error);
        deviceTypeList.value = [];
      });
  } catch (error) {
    console.error("页面初始化失败:", error);
  }
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 20px;
  background: $base-menu-background;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

// 主布局样式
.main-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 140px); // 减去顶部菜单和tab高度
  box-sizing: border-box;
}

// 左侧面板样式
.left-panel {
  flex: 0 0 400px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
  .panel-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px 8px 0 0;

    h3 {
      margin: 0;
      color: #2c3e50;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .tree-container {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
  }
}

// 右侧面板样式
.right-panel {
  flex: 1;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
  .panel-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px 8px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #2c3e50;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .device-list-container {
    flex: 1;
    padding: 16px 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .table-wrapper {
      flex: 1;
      overflow: hidden;
    }

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      flex: 1;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px dashed #d9d9d9;
    }
  }

  .save-actions {
    padding: 16px 20px;
    border-top: 1px solid #e4e7ed;
    text-align: right;
  }
}

// 设备筛选容器样式
.device-filter-container {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;

  .filter-row {
    .el-col {
      display: flex;
      align-items: center;
    }
  }
}

// 设备关联弹窗样式
.device-association-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.device-association-content {
  height: 60vh;
  display: flex;
  flex-direction: column;

  .search-section {
    padding: 20px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;

    .search-form {
      margin: 0;

      .el-form-item {
        margin-bottom: 0;
        margin-right: 16px;
      }
    }
  }

  .device-section {
    .search-form {
      padding: 16px;
      background: #ffffff;
      border-bottom: 1px solid #e4e7ed;

      .el-form {
        margin: 0;
      }

      .el-form-item {
        margin-bottom: 0;
        margin-right: 16px;
      }
    }
  }

  .main-content {
    flex: 1;
    padding: 20px;
    overflow: hidden;

    .content-row {
      height: 100%;
    }
  }

  .device-section {
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;

    .section-header {
      padding: 12px 16px;
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border-bottom: 1px solid #e4e7ed;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h4 {
        margin: 0;
        color: #2c3e50;
        font-size: 14px;
        font-weight: 600;
      }
    }

    .table-container {
      flex: 1;
      padding: 16px;
      overflow: hidden;
      display: flex;
      flex-direction: column;

      .el-table {
        flex: 1;
        margin-bottom: 16px;
      }

      .pagination {
        text-align: right;
        margin: 0;
        flex-shrink: 0;
      }
    }
  }
}

// 树选择器样式
:deep(.el-tree-select) {
  .el-select__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focused {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

// 输入框样式
:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

// 选择器样式
:deep(.el-select) {
  .el-select__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focused {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

// 数字输入框样式
:deep(.el-input-number) {
  .el-input__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

// 单选框组样式
:deep(.el-radio-group) {
  .el-radio {
    .el-radio__input {
      &.is-checked {
        .el-radio__inner {
          background-color: #4fdaca;
          border-color: #4fdaca;
        }
      }
    }

    .el-radio__label {
      color: #333333;
    }
  }
}

// 确认对话框样式
:deep(.el-message-box) {
  border-radius: 12px;

  .el-message-box__header {
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    color: #ffffff;
    border-radius: 12px 12px 0 0;

    .el-message-box__title {
      color: #ffffff;
    }
  }
}

// 不同类型标签的颜色样式
.custom-tag {
  &.group-factory {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    color: #ffffff;
    border: 1px solid #ff5252;
  }

  &.group-building {
    background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
    color: #ffffff;
    border: 1px solid #26a69a;
  }

  &.group-workshop {
    background: linear-gradient(135deg, #45b7d1 0%, #2196f3 100%);
    color: #ffffff;
    border: 1px solid #1976d2;
  }

  &.group-process {
    background: linear-gradient(135deg, #f9ca24 0%, #f0932b 100%);
    color: #ffffff;
    border: 1px solid #ff9800;
  }

  &.group-device {
    background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
    color: #ffffff;
    border: 1px solid #9c27b0;
  }

  &.energy-water {
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
    color: #ffffff;
    border: 1px solid #1976d2;
  }

  &.energy-electric {
    background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
    color: #ffffff;
    border: 1px solid #ff9800;
  }

  &.energy-gas {
    background: linear-gradient(135deg, #55a3ff 0%, #003d82 100%);
    color: #ffffff;
    border: 1px solid #2196f3;
  }

  &.energy-heat {
    background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%);
    color: #ffffff;
    border: 1px solid #e91e63;
  }
}
</style>
